package com.laikan.reader.bookstore.activity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.view.View;
import android.widget.*;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.laikan.library.components.activitys.BasicActivity;
import com.laikan.library.httpvolley.engine.HttpApiRequestEngine;
import com.laikan.library.httpvolley.engine.Requester;
import com.laikan.library.httpvolley.helper.RequestListener;
import com.laikan.library.httpvolley.helper.VolleyErrorHandler;
import com.laikan.library.httpvolley.response.HttpResponse;
import com.laikan.library.utils.SPUtil;
import com.laikan.reader.R;
import com.laikan.reader.comment.APIProtocol;
import com.laikan.reader.comment.Constants;
import com.laikan.reader.core.adapter.RankingAdapter;
import com.laikan.reader.core.bean.BaseDataBean;
import com.laikan.reader.core.bean.RankingBean;
import com.laikan.reader.core.utils.ActivityUitl;
import com.laikan.reader.core.utils.PublicUtil;
import com.laikan.reader.core.view.CircleProgressBar;
import com.socks.library.KLog;
import com.umeng.analytics.MobclickAgent;

import java.lang.reflect.Type;
import java.util.ArrayList;

import static com.laikan.reader.R.string.laikan_data_load_failed;
import static com.laikan.reader.R.string.laikan_network_anomaly;

/**
 * 排行界面
 * Created by gwt on 2016/10/19.
 */
public class RankingActivity extends BasicActivity {

    private ListView list_ranking;
    private TextView tv_title;
    private RelativeLayout rl_back_layout;
    private RelativeLayout common_loaddata_notice;
    private TextView common_prompt_content;
    private TextView common_refresh_net;
    private CircleProgressBar circleProgressBar;
    private Drawable drawable_back_tv;
    private ImageView iv_back;
    private LinearLayout ll_search_img;
    private RankingAdapter rankingAdapter;
    private long mLoadDelaynternalTime;
    private RankingBean rankingBean;
    private ImageView common_prompt_image;

    @Override
    protected void assignViews() {
        setContentView(R.layout.activity_ranking);
        rl_back_layout = (RelativeLayout)findViewById(R.id.rl_back_layout);
        iv_back = (ImageView)findViewById(R.id.iv_title_back);
        tv_title = (TextView)findViewById(R.id.tv_title);
        list_ranking = (ListView)findViewById(R.id.list_ranking);
        ll_search_img = (LinearLayout)findViewById(R.id.ll_search_img);
        //无网络连接
        common_prompt_image = (ImageView)findViewById(R.id.common_prompt_image);
        common_loaddata_notice = (RelativeLayout)findViewById(R.id.common_loaddata_notice);
        common_prompt_content = (TextView)findViewById(R.id.common_prompt_content);
        common_refresh_net = (TextView)findViewById(R.id.common_refresh_net);
        circleProgressBar = (CircleProgressBar)findViewById(R.id.comon_bgbar_loading);
    }

    @Override
    protected void initData() {
        tv_title.setText(R.string.book_ranking);
        drawable_back_tv = new BitmapDrawable(PublicUtil.getAlphaBitmap(PublicUtil.readBitMap(mContext, R.drawable.lk_back_small), Color.parseColor("#66ccdd")));
        iv_back.setImageDrawable(drawable_back_tv);

        ArrayList<RankingBean.DataBean> datas = new ArrayList<>();
        rankingAdapter = new RankingAdapter(mContext, datas);
        list_ranking.setAdapter(rankingAdapter);
        if(ActivityUitl.isNetworkAvailable(mContext)){
            getDataFromNet(true);
        }else{
            circleProgressBar.setVisibility(View.INVISIBLE);
            common_loaddata_notice.setVisibility(View.VISIBLE);
            common_prompt_content.setText(R.string.laikan_network_anomaly);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        list_ranking.setOnItemClickListener(new ItemClickListener());
        if(rankingBean != null){
            sortData(rankingBean);
        }
    }

    @Override
    protected void setListener() {
        rl_back_layout.setOnClickListener(this);
        ll_search_img.setOnClickListener(this);
        common_refresh_net.setOnClickListener(this);
        list_ranking.setOnItemClickListener(new ItemClickListener());
    }

    //条目点击
    private class ItemClickListener implements AdapterView.OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            list_ranking.setOnItemClickListener(null);
            Intent intent = new Intent(RankingActivity.this,RankCategoryActivity.class);
            if(rankingBean != null){
                RankingBean.DataBean dataBean = rankingBean.getBookList().get(position);
                intent.putExtra("title",dataBean.getRankName());    //标题
                intent.putExtra("rankUrl",dataBean.getRankUrl());   //排行url
                intent.putExtra("pageNo",dataBean.getPageNo());     //页数
                intent.putExtra("pageSize",dataBean.getPageSize()); //每页条数
                if(dataBean.getSeq() == 1){
                    MobclickAgent.onEvent(mContext, "jx-ph-nr");//精选-排行-男生热销榜
                }else if(dataBean.getSeq() == 2){
                    MobclickAgent.onEvent(mContext, "jx-ph-nvr");//精选-排行-女生热销榜
                }else if(dataBean.getSeq() == 3){
                    MobclickAgent.onEvent(mContext, "jx-ph-cbr");//精选-排行-出版热销榜
                }else if(dataBean.getSeq() == 4){
                    MobclickAgent.onEvent(mContext, "jx-ph-gxz");//精选-排行-更新字数榜
                }else if(dataBean.getSeq() == 5){
                    MobclickAgent.onEvent(mContext, "jx-ph-zzs");//精选-排行-字数排行榜
                }
            }
            startActivity(intent);
            //保存第一个排行类型
            if(rankingBean.getBookList()!=null){
                SPUtil.putInt("rankSeq",rankingBean.getBookList().get(position).getSeq());
            }

        }
    }

    @Override
    protected void onClickEvent(View view) {
        super.onClickEvent(view);
        switch (view.getId()) {
            case R.id.rl_back_layout:
                finish();
                break;
            case R.id.ll_search_img:
                startActivity( new Intent(RankingActivity.this,BookSearchActivity.class));
                break;
            case R.id.common_refresh_net:
                circleProgressBar.setVisibility(View.VISIBLE);
                mLoadDelaynternalTime = System.currentTimeMillis() + 2000;
                common_refresh_net.setOnClickListener(null);
                if(ActivityUitl.isNetworkAvailable(RankingActivity.this)){
                    getDataFromNet(false);
                }else {
                    closeCircle(System.currentTimeMillis());
                }
                break;
        }
    }

    //请求网络
    public void getDataFromNet(boolean isShow) {
        if(isShow){
//            showDialog();
            common_loaddata_notice.setVisibility(View.VISIBLE);
            common_prompt_content.setVisibility(View.GONE);
            common_refresh_net.setVisibility(View.GONE);
            common_prompt_image.setVisibility(View.GONE);
            circleProgressBar.setVisibility(View.VISIBLE);
        }
        RequestListener requestListener = new RequestListener() {
            BaseDataBean<RankingBean> result;

            @Override
            public void onPreExecute() {
                KLog.e("---------volley onPreExecute!!!");
            }

            @Override
            public void onSuccess(HttpResponse httpResponse) {

                Gson gson = new Gson();
                Type type = new TypeToken<BaseDataBean<RankingBean>>() {
                }.getType();
                try {
                    result = gson.fromJson(httpResponse.responseContent, type);
                    rankingBean = result.getData();
                    if (result != null) {
                        if (rankingBean == null || rankingBean.getBookList().size()== 0 || !Constants.RESULT_OK.equals(result.getResult())) {
                            KLog.e(result.getError_msg());
                            showErrorView(1);
                        }else {
                            //成功 排序数据
                            sortData(rankingBean);
                            closeErrorView();
                        }
                    }else {
                        showErrorView(1);
                    }
                }catch (JsonSyntaxException e) {
                    // 数据解析失败
                    showErrorView(1);
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                showErrorView(2);
            }

            @Override
            public void onFinish() {
//                dismissDialog();
            }
        };


        Requester requester = new Requester();
        requester.setUrl(APIProtocol.laikan_rank_home);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);
    }

    //排序数据
    private void sortData(RankingBean rankingBean) {
        if(rankingBean!= null){
            ArrayList<RankingBean.DataBean> data = (ArrayList<RankingBean.DataBean>)rankingBean.getBookList();
            int rankSeq = SPUtil.getInt("rankSeq", 0);//默认显示网络顺序
            if(data!=null){

                for (int i = 0; i < data.size(); i++) {

                    if(data.get(i).getSeq() == rankSeq){
                        RankingBean.DataBean temp = data.get(i);
                        data.remove(data.get(i));
                        data.add(0,temp);
                    }
                }
            }
            rankingAdapter.setDatas(data);
        }
    }

    /**
     *  设置错误布局的显示与隐藏
     * type为1  数据加载失败，type 为2  网络异常
     */
    String showContent;
    private void settingShowOrHide(int type){
        if(type == 1){
            showContent = getString(laikan_data_load_failed);
        }else if(type == 2){
            showContent = getString(laikan_network_anomaly);
        }
        common_loaddata_notice.setVisibility(View.VISIBLE);
        common_prompt_content.setVisibility(View.VISIBLE);
        common_prompt_image.setVisibility(View.VISIBLE);
        common_refresh_net.setVisibility(View.VISIBLE);
        circleProgressBar.setVisibility(View.INVISIBLE);
        common_prompt_content.setText(showContent);
    }
    /**
     * @param type 为1，数据加载失败，为2 网络异常
     */
    private void showErrorView(int type){
        settingShowOrHide(type);
        closeCircle(System.currentTimeMillis());
    }

    /**
     * 隐藏无网络的布局
     */
    private void closeErrorView(){
        circleProgressBar.setVisibility(View.GONE);
        common_loaddata_notice.setVisibility(View.GONE);
    }

    private void closeCircle(long currenttime){
        if(currenttime < mLoadDelaynternalTime){
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    requestDataResultHandle();
                }
            },1000);
        }else{
            requestDataResultHandle();
        }
    }
    private void requestDataResultHandle(){
        circleProgressBar.setVisibility(View.INVISIBLE);
        common_loaddata_notice.setVisibility(View.VISIBLE);
        common_refresh_net.setOnClickListener(RankingActivity.this);
    }
}
